<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--科室数据-->
            <el-col :span="3" :xs="20" style="width: 8%;border-right-style: solid;border-width: 1px">
                <div class="head-container">
                    <el-input v-model="deptName" placeholder="请输入科室账号" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px"/>
                </div>
                <div class="head-container">
                    <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode"
                             ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick"/>
                </div>
            </el-col>
            <!--教师数据-->
            <el-col :span="20" :xs="24" style="width: 92%">
                <!-- 查询字段选择器 -->
                <div class="query-selector" style="margin-bottom: 15px; padding: 10px; background: #f5f7fa; border-radius: 4px;">
                    <el-select v-model="selectedQueryFields" multiple placeholder="请选择查询字段" style="width: 300px;">
                        <el-option label="教师账号" value="userName"/>
                        <el-option label="教师姓名" value="nickName"/>
                        <el-option label="身份证" value="identity"/>
                        <el-option label="性别" value="sex"/>
                        <el-option label="出生日期" value="birthday"/>
                        <el-option label="联系方式" value="phonenumber"/>
                        <el-option label="教师状态" value="status"/>
                        <el-option label="所属学科" value="base"/>
                        <el-option label="所属学校" value="school"/>
                        <el-option label="所属职称" value="post"/>
                        <el-option label="民族" value="nation"/>
                        <el-option label="籍贯" value="nativePlace"/>
                        <el-option label="入党时间" value="partyJoiningTime"/>
                        <el-option label="入伍时间" value="enlistmentTime"/>
                        <el-option label="入伍地" value="enlistmentPlace"/>
                        <el-option label="学历学位" value="educationDegreeId"/>
                        <el-option label="血型" value="bloodType"/>
                        <el-option label="人员类别" value="personnelCategoryId"/>
                        <el-option label="保障卡号" value="securityCardNo"/>
                        <el-option label="军人证件号" value="militaryIdNo"/>
                        <el-option label="创建时间" value="createTime"/>
                    </el-select>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" style="margin-left: 10px;">查询</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" style="margin-left: 10px;">重置</el-button>
                </div>

                <!-- 动态查询表单 -->
                <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" size="mini">
                    <!-- 教师账号 -->
                    <el-form-item v-if="selectedQueryFields.includes('userName')" label="教师账号" prop="userName">
                        <el-input v-model="queryParams.userName" placeholder="请输入教师账号" clearable style="width: 150px;" @keyup.enter.native="handleQuery"/>
                    </el-form-item>

                    <!-- 教师姓名 -->
                    <el-form-item v-if="selectedQueryFields.includes('nickName')" label="教师姓名" prop="nickName">
                        <el-input v-model="queryParams.nickName" placeholder="请输入教师姓名" clearable style="width: 150px;" @keyup.enter.native="handleQuery"/>
                    </el-form-item>

                    <!-- 身份证 -->
                    <el-form-item v-if="selectedQueryFields.includes('identity')" label="身份证" prop="identity">
                        <el-input v-model="queryParams.identity" placeholder="请输入身份证号" clearable style="width: 180px;" @keyup.enter.native="handleQuery"/>
                    </el-form-item>

                    <!-- 性别 -->
                    <el-form-item v-if="selectedQueryFields.includes('sex')" label="性别" prop="sex">
                        <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable style="width: 100px;">
                            <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value"/>
                        </el-select>
                    </el-form-item>

                    <!-- 出生日期 -->
                    <el-form-item v-if="selectedQueryFields.includes('birthday')" label="出生日期" prop="birthday">
                        <el-date-picker v-model="birthdayRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" clearable
                                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
                    </el-form-item>

                    <!-- 联系方式 -->
                    <el-form-item v-if="selectedQueryFields.includes('phonenumber')" label="联系方式" prop="phonenumber">
                        <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable style="width: 150px;" @keyup.enter.native="handleQuery"/>
                    </el-form-item>

                    <!-- 教师状态 -->
                    <el-form-item v-if="selectedQueryFields.includes('status')" label="教师状态" prop="status">
                        <el-select v-model="queryParams.status" placeholder="教师状态" clearable style="width: 120px;">
                            <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value"/>
                        </el-select>
                    </el-form-item>

                    <!-- 所属学科 -->
                    <el-form-item v-if="selectedQueryFields.includes('base')" label="所属学科">
                        <el-select v-model="queryParams.params.base" placeholder="请选择所属学科" style="width: 150px;" clearable>
                            <el-option v-for="item in baseList" :key="item.id" :label="item.name" :value="item.id"/>
                        </el-select>
                    </el-form-item>

                    <!-- 所属学校 -->
                    <el-form-item v-if="selectedQueryFields.includes('school')" label="所属学校">
                        <el-select v-model="queryParams.params.school" placeholder="请选择所属学校" style="width: 150px;" clearable>
                            <el-option v-for="item in schoolList" :key="item.id" :label="item.name" :value="item.id"/>
                        </el-select>
                    </el-form-item>

                    <!-- 所属职称 -->
                    <el-form-item v-if="selectedQueryFields.includes('post')" label="所属职称">
                        <el-select v-model="queryParams.params.post" placeholder="请选择职称" style="width: 150px;" clearable>
                            <el-option v-for="dict in dict.type.basic_post_teacher_dict" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
                        </el-select>
                    </el-form-item>

                    <!-- 民族 -->
                    <el-form-item v-if="selectedQueryFields.includes('nation')" label="民族">
                        <el-input v-model="queryParams.params.nation" placeholder="请输入民族" clearable style="width: 120px;" @keyup.enter.native="handleQuery"/>
                    </el-form-item>

                    <!-- 籍贯 -->
                    <el-form-item v-if="selectedQueryFields.includes('nativePlace')" label="籍贯">
                        <el-input v-model="queryParams.params.nativePlace" placeholder="请输入籍贯" clearable style="width: 150px;" @keyup.enter.native="handleQuery"/>
                    </el-form-item>

                    <!-- 入党时间 -->
                    <el-form-item v-if="selectedQueryFields.includes('partyJoiningTime')" label="入党时间">
                        <el-date-picker v-model="partyJoiningTimeRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" clearable
                                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                    </el-form-item>

                    <!-- 入伍时间 -->
                    <el-form-item v-if="selectedQueryFields.includes('enlistmentTime')" label="入伍时间">
                        <el-date-picker v-model="enlistmentTimeRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" clearable
                                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                    </el-form-item>

                    <!-- 入伍地 -->
                    <el-form-item v-if="selectedQueryFields.includes('enlistmentPlace')" label="入伍地">
                        <el-input v-model="queryParams.params.enlistmentPlace" placeholder="请输入入伍地" clearable style="width: 150px;" @keyup.enter.native="handleQuery"/>
                    </el-form-item>

                    <!-- 学历 -->
                    <el-form-item v-if="selectedQueryFields.includes('educationId')" label="学历">
                        <el-select v-model="queryParams.params.educationId" placeholder="请选择学历" style="width: 120px;" clearable>
                            <el-option v-for="dict in dict.type.basic_educatiod_dict" :key="dict.value" :label="dict.label" :value="dict.value"/>
                        </el-select>
                    </el-form-item>

                    <!-- 学位 -->
                    <el-form-item v-if="selectedQueryFields.includes('degreeId')" label="学位">
                        <el-select v-model="queryParams.params.degreeId" placeholder="请选择学位" style="width: 120px;" clearable>
                            <el-option v-for="dict in dict.type.basic_degree_dict" :key="dict.value" :label="dict.label" :value="dict.value"/>
                        </el-select>
                    </el-form-item>

                    <!-- 血型 -->
                    <el-form-item v-if="selectedQueryFields.includes('bloodType')" label="血型">
                        <el-select v-model="queryParams.params.bloodType" placeholder="请选择血型" style="width: 100px;" clearable>
                            <el-option label="A" value="A"/>
                            <el-option label="B" value="B"/>
                            <el-option label="AB" value="AB"/>
                            <el-option label="O" value="O"/>
                            <el-option label="其他" value="其他"/>
                        </el-select>
                    </el-form-item>

                    <!-- 人员类别 -->
                    <el-form-item v-if="selectedQueryFields.includes('personnelCategoryId')" label="人员类别">
                        <el-select v-model="queryParams.params.personnelCategoryId" placeholder="请选择人员类别" style="width: 120px;" clearable>
                            <el-option v-for="dict in dict.type.user_type_dict" :key="dict.value" :label="dict.label" :value="dict.value"/>
                        </el-select>
                    </el-form-item>

                    <!-- 保障卡号 -->
                    <el-form-item v-if="selectedQueryFields.includes('securityCardNo')" label="保障卡号">
                        <el-input v-model="queryParams.params.securityCardNo" placeholder="请输入保障卡号" clearable style="width: 150px;" @keyup.enter.native="handleQuery"/>
                    </el-form-item>

                    <!-- 军人证件号 -->
                    <el-form-item v-if="selectedQueryFields.includes('militaryIdNo')" label="军人证件号">
                        <el-input v-model="queryParams.params.militaryIdNo" placeholder="请输入军人证件号" clearable style="width: 150px;" @keyup.enter.native="handleQuery"/>
                    </el-form-item>

                    <!-- 创建时间 -->
                    <el-form-item v-if="selectedQueryFields.includes('createTime')" label="创建时间">
                        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" clearable
                                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:teacher:add']">新增</el-button>
                    </el-col>
<!--                    <el-col :span="1.5">-->
<!--                        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:user:edit']">修改</el-button>-->
<!--                    </el-col>-->
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:user:remove']">删除</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="info" plain icon="el-icon-upload" size="mini" @click="handleImport" v-hasPermi="['system:teacher:import']">导入</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:teacher:export']">导出</el-button>
                    </el-col>
                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/>
                </el-row>

                <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" @sort-change="handleSortChange" :default-sort="{prop: 'createTime', order: 'descending'}">
                    <el-table-column type="selection" width="50" align="center"/>
                    <!--                    <el-table-column label="教师编号" align="center" key="userId" prop="userId"/>-->
                    <!--                    <el-table-column label="教师账号" align="center" key="userName" prop="userName" show-overflow-tooltip/>-->
                    <el-table-column label="教师姓名" align="center" key="nickName" prop="nickName" show-overflow-tooltip sortable="custom"/>
                    <!--                    <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" show-overflow-tooltip/>-->
                    <el-table-column label="身份证" align="center" key="identity" prop="identity" show-overflow-tooltip sortable="custom"/>
                    <el-table-column label="性别" align="center" key="sex" prop="sex">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
                        </template>
                    </el-table-column>
                    <el-table-column label="科室" align="center" key="deptName" prop="dept.deptName" show-overflow-tooltip sortable="custom"/>
                    <el-table-column label="民族" align="center" prop="militaryUser.nation"/>
                    <el-table-column label="籍贯" align="center" prop="militaryUser.nativePlace" />
                    <el-table-column label="入伍时间" align="center" prop="militaryUser.enlistmentTime" show-overflow-tooltip sortable="custom">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.militaryUser?.enlistmentTime,'{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="入党时间" align="center" prop="militaryUser.partyJoiningTime" show-overflow-tooltip sortable="custom">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.militaryUser?.partyJoiningTime,'{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="入伍地" align="center" prop="militaryUser.enlistmentPlace" />

<!--                    <el-table-column label="学历" align="center" key="militaryUser.educationDegreeId" prop="militaryUser.educationDegreeId" >-->
<!--                        <template slot-scope="scope">-->
<!--                            <dict-tag :options="dict.type.basic_educatiod_dict" :value="scope.row.militaryUser.educationId"/>-->
<!--                        </template>-->
<!--                    </el-table-column>-->
<!--                    <el-table-column label="学位" align="center" key="militaryUser.educationDegreeId" prop="militaryUser.educationDegreeId" >-->
<!--                        <template slot-scope="scope">-->
<!--                            <dict-tag :options="dict.type.basic_educatiod_dict" :value="scope.row.militaryUser.degreeId"/>-->
<!--                        </template>-->
<!--                    </el-table-column>-->

                    <el-table-column label="学历/学位" align="center" key="militaryUser.educationDegreeId" prop="militaryUser.educationDegreeId">
                        <template slot-scope="scope">
                            <span>
                                {{ getDictLabel(dict.type.basic_educatiod_dict, scope.row.militaryUser.educationId) }}/{{ getDictLabel(dict.type.basic_degree_dict, scope.row.militaryUser.degreeId) }}
                            </span>
                        </template>
                    </el-table-column>

<!--                    <el-table-column label="血型" align="center" prop="militaryUser.bloodType" show-overflow-tooltip sortable="custom"/>-->
                    <el-table-column label="血型" align="center" key="militaryUser.bloodType" prop="militaryUser.bloodType" show-overflow-tooltip sortable="custom">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.basic_blood_type_dict" :value="scope.row.militaryUser.bloodType"/>
                        </template>
                    </el-table-column>
                    <el-table-column label="人员类别" align="center" key="militaryUser.personnelCategoryId" prop="militaryUser.personnelCategoryId" show-overflow-tooltip sortable="custom">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.user_type_dict" :value="scope.row.militaryUser.personnelCategoryId"/>
                        </template>
                    </el-table-column>

                    <el-table-column label="保障卡号" align="center" prop="militaryUser.securityCardNo" show-overflow-tooltip sortable="custom"/>
                    <el-table-column label="军人证件号" align="center" prop="militaryUser.militaryIdNo" show-overflow-tooltip sortable="custom"/>
                    <el-table-column label="总支" align="center" prop="militaryUser.organizationalCategory"/>
                    <el-table-column label="部职别" align="center" prop="militaryUser.dutyTitle" />
                    <el-table-column label="状态" align="center" key="status">
                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" inactive-color="red" @change="handleStatusChange(scope.row)"></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime,'{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" min-width="150" class-name="small-padding fixed-width">
                        <template slot-scope="scope" v-if="scope.row.userId !== 1 && scope.row.userId != loginUserId">
                            <!-- 已删除状态显示找回按钮 -->
                            <template v-if="scope.row.delFlag === '2'">
                                <el-button size="mini" type="text" icon="el-icon-refresh-left" @click="handleRecover(scope.row)" v-hasPermi="['system:user:remove']">找回
                                </el-button>
                            </template>
                            <!-- 正常状态显示原有操作按钮 -->
                            <template v-else>
                                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                                           v-hasPermi="['system:user:edit']">修改
                                </el-button>
                                <el-button v-if="scope.row.userId != loginUserId" size="mini" type="text"
                                           icon="el-icon-delete" @click="handleDelete(scope.row)"
                                           v-hasPermi="['system:user:remove']">删除
                                </el-button>
                            </template>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>
            </el-col>
        </el-row>

        <!-- 添加或修改教师配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-row v-if="form.userId == undefined" :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="学生账号" prop="userName">
                            <el-input v-model="form.userName" placeholder="请输入学生账号" maxlength="30" style="width: 100%"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="学生密码" prop="password">
                            <el-input v-model="form.password" placeholder="请输入学生密码" type="password" maxlength="20" show-password style="width: 100%"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="学生姓名" prop="nickName">
                            <el-input v-model="form.nickName" placeholder="请输入学生姓名" maxlength="30" style="width: 100%"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="归属科室" prop="deptId">
                            <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属科室" style="width: 100%"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="手机号码" prop="phonenumber">
                            <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" style="width: 100%"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="身份证" prop="identity">
                            <el-input v-model="form.identity" placeholder="请输入身份证" maxlength="32" style="width: 100%"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="学生性别">
                            <el-radio-group v-model="form.sex">
                                <el-radio v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="总支" prop="militaryUser.organizationalCategory">
                            <el-input v-model="form.militaryUser.organizationalCategory" placeholder="请输入总支" maxlength="50" style="width: 100%"/>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 军人信息 -->
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="民族" prop="militaryUser.nation">
                            <el-input v-model="form.militaryUser.nation" placeholder="请输入民族" maxlength="20" style="width: 100%"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="籍贯" prop="militaryUser.nativePlace">
                            <el-input v-model="form.militaryUser.nativePlace" placeholder="请输入籍贯" maxlength="50" style="width: 100%"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="入伍时间" prop="militaryUser.enlistmentTime">
                            <el-date-picker v-model="form.militaryUser.enlistmentTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择入伍时间" style="width: 100%"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入党(团)时间" prop="militaryUser.partyJoiningTime">
                            <el-date-picker v-model="form.militaryUser.partyJoiningTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择入党(团)时间" style="width: 100%"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="学历" prop="militaryUser.educationId">
                            <el-select v-model="form.militaryUser.educationId" placeholder="请选择学历" style="width: 100%">
                                <el-option v-for="dict in dict.type.basic_educatiod_dict" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="学位" prop="militaryUser.degreeId">
                            <el-select v-model="form.militaryUser.degreeId" placeholder="请选择学位" style="width: 100%">
                                <el-option v-for="dict in dict.type.basic_degree_dict" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="血型" prop="militaryUser.bloodType">
                            <el-select v-model="form.militaryUser.bloodType" placeholder="请选择血型" style="width: 100%">
                                <el-option v-for="dict in dict.type.basic_blood_type_dict" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="人员类别" prop="militaryUser.personnelCategoryId">
                            <el-select v-model="form.militaryUser.personnelCategoryId" placeholder="请选择人员类别" style="width: 100%">
                                <el-option v-for="dict in dict.type.user_type_dict" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="保障卡号" prop="militaryUser.securityCardNo">
                            <el-input v-model="form.militaryUser.securityCardNo" placeholder="请输入保障卡号" maxlength="20" style="width: 100%"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="军人证件号码" prop="militaryUser.militaryIdNo">
                            <el-input v-model="form.militaryUser.militaryIdNo" placeholder="请输入军人证件号码" maxlength="20" style="width: 100%"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">

                    <el-col :span="12">
                        <el-form-item label="入伍地" prop="militaryUser.enlistmentPlace">
                            <el-input v-model="form.militaryUser.enlistmentPlace" placeholder="请输入入伍地" maxlength="50" style="width: 100%"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="部职别" prop="militaryUser.dutyTitle">
                            <el-input v-model="form.militaryUser.dutyTitle" placeholder="请输入部职别" maxlength="50" style="width: 100%"/>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入内容" style="width: 100%"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 教师导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport"
                       :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <div class="el-upload__tip" slot="tip">
                        <el-checkbox v-model="upload.updateSupport"/>
                        是否更新已经存在的教师数据
                    </div>
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 导出字段选择对话框 -->
        <el-dialog title="选择导出字段" :visible.sync="exportDialogVisible" width="580px" append-to-body>
            <div>
                <el-row :gutter="20">
                    <el-col :span="12" v-for="(field, index) in exportFields" :key="field.value" :offset="index % 2 === 0 ? 0 : 0">
                        <div style="display: flex; align-items: center; margin-bottom: 10px;">
                            <el-checkbox :checked="field.checked" @change="(checked) => {
                                const targetField = exportFields.find(item => item.value === field.value);
                                if (targetField) targetField.checked = checked;
                            }">
                                {{ field.label }}
                            </el-checkbox>
                            <el-checkbox v-if="field.encrypt" v-model="field.encryptChecked" style="margin-left: 10px; font-size: 12px;">
                                加密显示
                            </el-checkbox>
                        </div>
                    </el-col>
                </el-row>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="exportDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmExport">确认导出</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    getUser,
    delUser,
    updateUser,
    resetUserPwd,
    changeUserStatus,
    deptTreeSelect,
    recoverUser
} from "@/api/system/user";
import {addTeacher, listTeacher} from "@/api/system/teacher";
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listBase} from "@/api/basic/base";
import {listSchool} from "@/api/basic/school";
import {copyObj} from "@/utils/zzDouUtils/objUtil";
import {nowDateStr} from "@/utils/zzDouUtils/dateUtil";

var pageForm = {pageSize:1000,pageNum:1}
export default {
    name: "User",
    dicts: ['sys_normal_disable', 'sys_user_sex','basic_post_teacher_dict' ,'user_type_dict' ,'basic_educatiod_dict','basic_degree_dict', 'basic_education_degree_dict', 'basic_blood_type_dict', 'basic_personnel_category_dict'],
    components: {Treeselect},
    data() {
        return {
            //学科列表
            baseList:null,
            schoolList:null,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 教师表格数据
            userList: null,
            // 弹出层标题
            title: "",
            // 科室树选项
            deptOptions: undefined,
            // 是否显示弹出层
            open: false,
            // 科室账号
            deptName: undefined,
            // 默认密码
            initPassword: undefined,
            // 日期范围
            dateRange: [],
            birthdayRange: [],
            partyJoiningTimeRange: [],
            enlistmentTimeRange: [],
            // 选中的查询字段
            selectedQueryFields: [],
            // 导出字段选择对话框
            exportDialogVisible: false,
            // 导出字段列表
            exportFields: [
                // 基本信息（第一列）
                { label: '登录账户', value: 'userName', checked: true },
                { label: '教师姓名', value: 'nickName', checked: true },
                { label: '民族', value: 'nation', checked: true },
                { label: '用户性别', value: 'sex', checked: true },
                { label: '籍贯', value: 'nativePlace', checked: true },
                { label: '入伍时间', value: 'enlistmentTime', checked: true },
                // 基本信息（第二列）
                { label: '所属科室', value: 'deptName', checked: true },
                { label: '入党时间', value: 'partyJoiningTime', checked: true },
                { label: '入伍地', value: 'enlistmentPlace', checked: true },
                { label: '学历学位', value: 'educationDegreeId', checked: true },
                { label: '血型', value: 'bloodType', checked: true },
                { label: '人员类别', value: 'personnelCategoryId', checked: true },

                // 其他信息
                { label: '总支', value: 'organizationalCategory', checked: true },
                { label: '部职别', value: 'dutyTitle', checked: true },

                // 加密字段
                { label: '保障卡号', value: 'securityCardNo', checked: true, encrypt: true, encryptChecked: false },
                { label: '身份证', value: 'identity', checked: true, encrypt: true, encryptChecked: false },
                { label: '手机号码', value: 'phonenumber', checked: true, encrypt: true, encryptChecked: false },
                { label: '军人证件号', value: 'militaryIdNo', checked: true, encrypt: true, encryptChecked: false },

                ],
            // 岗位选项
            postOptions: [],
            // 角色选项
            roleOptions: [],
            // 表单参数
            form: {
                userInfo:{},
                militaryUser: {}
            },
            defaultProps: {
                children: "children",
                label: "label"
            },
            // 教师导入参数
            upload: {
                // 是否显示弹出层（教师导入）
                open: false,
                // 弹出层标题（教师导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的教师数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: {Authorization: "Bearer " + getToken()},
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/system/teacher/importData"
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                userName: null,
                phonenumber: null,
                status: null,
                deptId: null,
                params:{},
            },
            // 排序字段
            sortField: '',
            // 排序方式
            sortOrder: '',
            // 表单校验
            rules: {
                userName: [
                    {required: true, message: "教师账号不能为空", trigger: "blur"},
                    {min: 2, max: 20, message: '教师账号长度必须介于 2 和 20 之间', trigger: 'blur'}
                ],
                nickName: [
                    {required: true, message: "教师姓名不能为空", trigger: "blur"}
                ],
                password: [
                    {required: true, message: "教师密码不能为空", trigger: "blur"},
                    {min: 5, max: 20, message: '教师密码长度必须介于 5 和 20 之间', trigger: 'blur'}
                ],
                email: [
                    {type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"]}
                ],
                phonenumber: [
                    {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
                ],
                identity: [
                    {pattern: /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: "请输入正确的身份证号", trigger: "blur"}
                ],
                'militaryUser.nation': [
                    {required: true, message: "民族不能为空", trigger: "blur"}
                ],
                'militaryUser.nativePlace': [
                    {required: true, message: "籍贯不能为空", trigger: "blur"}
                ],
                'militaryUser.enlistmentTime': [
                    {required: true, message: "入伍时间不能为空", trigger: "change"}
                ],
                'militaryUser.partyJoiningTime': [
                    {required: true, message: "入党(团)时间不能为空", trigger: "change"}
                ],
                'militaryUser.enlistmentPlace': [
                    {required: true, message: "入伍地不能为空", trigger: "blur"}
                ],
                'militaryUser.educationDegreeId': [
                    {required: true, message: "学历学位不能为空", trigger: "change"}
                ],
                'militaryUser.bloodType': [
                    {required: true, message: "血型不能为空", trigger: "change"}
                ],
                'militaryUser.personnelCategoryId': [
                    {required: true, message: "人员类别不能为空", trigger: "change"}
                ],
                'militaryUser.securityCardNo': [
                    {required: true, message: "保障卡号不能为空", trigger: "blur"}
                ],
                'militaryUser.militaryIdNo': [
                    {required: true, message: "军人证件号码不能为空", trigger: "blur"}
                ],
                'militaryUser.organizationalCategory': [
                    {required: true, message: "总支不能为空", trigger: "blur"}
                ],
                'militaryUser.dutyTitle': [
                    {required: true, message: "部职别不能为空", trigger: "blur"}
                ]
            }
        };
    },
    watch: {
        // 根据账号筛选科室树
        deptName(val) {
            this.$refs.tree.filter(val);
        }
    },
    created() {
        this.getList();
        this.getDeptTree();
        this.getConfigKey("sys.user.initPassword").then(response => {
            this.initPassword = response.msg;
        });
        this.getListBase();
        this.getListSchool();
    },
    methods: {
        /** 查询教师列表 */
        getList() {
            this.loading = true;
            let data = JSON.parse(JSON.stringify(this.queryParams)); // 深拷贝查询参数

            // 添加日期范围查询
            data = this.addDateRange(data, this.dateRange); // 创建时间
            data = this.addDateRange(data, this.birthdayRange, 'Birthday'); // 生日
            data = this.addDateRange(data, this.partyJoiningTimeRange, 'PartyJoiningTime'); // 入党时间
            data = this.addDateRange(data, this.enlistmentTimeRange, 'EnlistmentTime'); // 入伍时间

            // 清理未选中字段的值，避免影响查询
            const allQueryFields = ['userName', 'nickName', 'identity', 'sex', 'phonenumber', 'status'];
            const allParamsFields = ['base', 'school', 'post', 'nation', 'nativePlace', 'enlistmentPlace', 'educationId','degreeId', 'bloodType', 'personnelCategoryId', 'securityCardNo', 'militaryIdNo'];

            // 清理一级字段
            allQueryFields.forEach(field => {
                if (!this.selectedQueryFields.includes(field)) {
                    data[field] = null;
                }
            });

            // 清理params中的字段
            allParamsFields.forEach(field => {
                if (!this.selectedQueryFields.includes(field)) {
                    if (data.params[field]) {
                        data.params[field] = null;
                    }
                }
            });
            // 添加排序参数
            if (this.sortField) {
                if (!data.params) {
                    data.params = {};
                }
                // 将前端驼峰命名转换为数据库下划线命名
                let columnName = this.sortField;

                // 处理嵌套属性（如militaryUser.securityCardNo）
                if (columnName.includes('.')) {
                    const parts = columnName.split('.');
                    const objectName = parts[0];
                    const fieldName = parts[1];

                    // 将字段名从驼峰转下划线
                    const underscoreField = fieldName.replace(/([A-Z])/g, '_$1').toLowerCase();

                    // 根据对象名确定表别名
                    if (objectName === 'militaryUser') {
                        columnName = 'm.' + underscoreField; // 使用m表别名（sys_military_user）
                    } else if (objectName === 'dept') {
                        columnName = 'd.' + underscoreField; // 使用d表别名（sys_dept）
                    } else if (objectName === 'userInfo') {
                        columnName = 'i.' + underscoreField; // 使用i表别名（sys_user_info）
                    }
                }
                // 特殊处理部门名称字段
                else if (columnName.includes('dept') || columnName === 'deptName') {
                    columnName = 'd.dept_name'; // 使用d表别名
                }
                // 特殊处理创建时间字段
                else if (columnName === 'createTime') {
                    columnName = 'u.`create_time`';
                }
                // 其他用户表字段
                else {
                    // 一般字段转换规则：驼峰转下划线
                    columnName = columnName.replace(/([A-Z])/g, '_$1').toLowerCase();
                    // 为用户表字段添加表别名'u.'
                    columnName = 'u.' + columnName;
                }

                data.params.orderByColumn = columnName;
                data.params.isAsc = this.sortOrder === 'ascending' ? 'asc' : 'desc';
            }
            listTeacher(data).then(response => {
                    this.userList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                }
            );
        },
        // 处理排序变化
        handleSortChange({ column, prop, order }) {
            this.sortField = prop;
            this.sortOrder = order;
            this.getList();
        },
        /** 查询科室下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then(response => {
                this.deptOptions = response.data;
            });
        },
        // 筛选节点
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        // 节点单击事件
        handleNodeClick(data) {
            this.queryParams.deptId = data.id;
            this.handleQuery();
        },
        // 教师状态修改
        handleStatusChange(row) {
            let text = row.status === "0" ? "启用" : "停用";
            this.$modal.confirm('确认要 ' + text + ' ' + row.nickName + ' 教师吗？').then(function () {
                return changeUserStatus(row.userId, row.status);
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
            }).catch(function () {
                row.status = row.status === "0" ? "1" : "0";
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                userId: null,
                deptId: null,
                userName: null,
                nickName: null,
                password:  this.initPassword,
                phonenumber: null,
                email: null,
                sex: null,
                status: "0",
                remark: null,
                postIds: [],
                roleIds: [],
                userInfo:{},
                militaryUser: {
                    nation: null,
                    nativePlace: null,
                    enlistmentTime: null,
                    partyJoiningTime: null,
                    enlistmentPlace: null,
                    educationDegreeId: null,
                    bloodType: null,
                    personnelCategoryId: null,
                    securityCardNo: null,
                    militaryIdNo: null,
                    organizationalCategory: null,
                    dutyTitle: null
                }
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.birthdayRange = [];
            this.partyJoiningTimeRange = [];
            this.enlistmentTimeRange = [];
            this.selectedQueryFields = [];
            this.resetForm("queryForm");
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                userName: null,
                phonenumber: null,
                status: null,
                deptId: null,
                params:{},
            };
            this.$refs.tree.setCurrentKey(null);
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.userId);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        // 更多操作触发
        handleCommand(command, row) {
            switch (command) {
                case "handleResetPwd":
                    this.handleResetPwd(row);
                    break;
                case "handleAuthRole":
                    this.handleAuthRole(row);
                    break;
                default:
                    break;
            }
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            getUser().then(response => {
                // this.postOptions = response.posts;
                // this.roleOptions = response.roles;
                this.open = true;
                this.title = "添加教师";
                this.form.password = this.initPassword;
            });
        },
        /** 找回按钮操作 */
        handleRecover(row) {
            this.$modal.confirm('确定要找回用户"' + row.nickName + '"吗？').then(() => {
                // 这里应该调用后端的恢复接口
                return recoverUser(row.userId);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("找回成功");
            }).catch(() => {
                // 取消找回
            });
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.form = copyObj(row);
            this.form.userInfo = copyObj(row.userInfo);
            this.form.militaryUser = copyObj(row.militaryUser || {});
            this.open = true;
            this.title = "修改教师";
            this.form.password = "";
        },
        /** 重置密码按钮操作 */
        handleResetPwd(row) {
            this.$prompt('请输入"' + row.nickName + '"的新密码', "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                closeOnClickModal: false,
                inputPattern: /^.{5,20}$/,
                inputErrorMessage: "教师密码长度必须介于 5 和 20 之间"
            }).then(({value}) => {
                resetUserPwd(row.userId, value).then(response => {
                    this.$modal.msgSuccess("修改成功，新密码是：" + value);
                });
            }).catch(() => {
            });
        },
        /** 分配角色操作 */
        handleAuthRole: function (row) {
            const userId = row.userId;
            this.$router.push("/system/user-auth/role/" + userId);
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.userId != undefined) {
                        updateUser(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addTeacher(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const userIds = row.userId || this.ids;
            this.$modal.confirm('是否确认删除教师编号为"' + userIds + '"的数据项？').then(function () {
                return delUser(userIds);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        /** 导出按钮操作 - 打开导出字段选择对话框 */
        handleExport() {
            this.exportDialogVisible = true;
        },
        // 确认导出
        confirmExport() {
            // 获取选中的导出字段
            const selectedFields = this.exportFields
                .filter(field => field.checked)
                .map(field => field.value);

            // 验证至少选择一个字段
            if (selectedFields.length === 0) {
                this.$modal.msgWarning('请至少选择一个导出字段');
                return;
            }

            // 获取需要加密的字段
            const encryptFields = this.exportFields
                .filter(field => field.checked && field.encrypt && field.encryptChecked)
                .map(field => field.value);

            // 关闭对话框并执行导出
            this.exportDialogVisible = false;

            // 发送导出请求，带上选中的字段信息和加密选项
            this.download('system/teacher/export', {
                ...this.queryParams,
                exportFields: selectedFields.join(','), // 将选中的字段拼接成字符串
                encryptFields: encryptFields.join(',')  // 将需要加密的字段拼接成字符串
            }, `教师_${nowDateStr()}.xlsx`);
        },
        /** 导入按钮操作 */
        handleImport() {
            this.upload.title = "教师导入";
            this.upload.open = true;
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download('system/teacher/importTemplate', {}, `教师模板_${nowDateStr()}.xlsx`)
        },

        getDictLabel(dictOptions, value) {
            if (!dictOptions || !value) return '';
            const dict = dictOptions.find(item => item.value === String(value));
            return dict ? dict.label : '';
        },

        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            // 创建一个新的对话框实例，使用更大的宽度和适当的样式
            this.$alert("<div style='overflow: auto;max-width: none;min-width: 900px;max-height: 70vh;padding: 10px 20px 0;white-space: pre-wrap;word-break: break-word;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true, customClass: 'wide-alert', center: false});
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
        //------------------------------------------------
        /** 查询学科表列表 */
        getListBase() {
            listBase(pageForm).then(response => {
                this.baseList = response.rows;
            });
        },
        /** 查询学校表列表 */
        getListSchool() {
            listSchool(pageForm).then(response => {
                this.schoolList = response.rows;
            });
        },
    }
};
</script>
<style>
/* 为导入结果弹窗添加宽样式 */
.wide-alert {
    width: 700px !important;
    max-width: none !important;
}
.wide-alert .el-message-box__content {
    padding: 20px;
}
</style>
